package handlers

import (
	"net/http"
	"strings"
	"supply-chain/models"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type DealerHandler struct {
	DB *gorm.DB
}

// RequestProduct 处理商品请求
func (h *DealerHandler) RequestProduct(c *gin.Context) {
	var request ProductRequest
	if err := c.ShouldBindJSON(&request); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 查找已生产的商品
	var product models.Product
	if err := h.DB.Where("name = ? AND status = ?", request.ProductName, "produced").First(&product).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Product not available"})
		return
	}

	// 更新商品状态和转移信息
	product.Status = "delivered"
	product.Trans = product.Trans + "->dealer"

	if err := h.DB.Save(&product).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update product status"})
		return
	}

	c.JSON(http.StatusOK, product)
}

// GetProductTrace 获取商品溯源信息
func (h *DealerHandler) GetProductTrace(c *gin.Context) {
	epcID := c.Param("epc_id")
	var product models.Product

	if err := h.DB.Where("epc_id = ?", epcID).First(&product).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Product not found"})
		return
	}

	// 获取原材料溯源信息
	materialEPCs := strings.Split(product.MaterialEPCs, ",")
	var materials []models.Material

	if err := h.DB.Where("epc_id IN ?", materialEPCs).Find(&materials).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch materials"})
		return
	}

	if len(materials) == 0 {
		c.JSON(http.StatusNotFound, gin.H{"error": "Materials not found"})
		return
	}

	trace := gin.H{
		"product":   product,
		"materials": materials,
	}

	c.JSON(http.StatusOK, trace)
}

